import random
import string
from Crypto.Cipher import AES
from Crypto.Util.Padding import pad, unpad
import base64

# 生成指定长度的随机字符串
def random_string(length=64):
    # 随机字符串的取值，去除了9g1i2z等一些容易混淆的字符
    chars = 'ABCDEFGHJKMNPQRSTWXYZabcdefhijkmnprstwxyz2345678'
    return ''.join(random.choice(chars) for _ in range(length))

# AES加密
def aes_encrypt(message, key):
    # 将消息和密钥转换为字节
    key = key.encode('utf-8')
    message = message.encode('utf-8')

    # 使用AES进行加密
    cipher = AES.new(key, AES.MODE_ECB)
    encrypted_data = cipher.encrypt(pad(message, AES.block_size))

    # 将加密后的数据转换为Base64编码
    return base64.b64encode(encrypted_data).decode('utf-8')

# AES解密
def aes_decrypt(message_base64, key):
    # 将Base64编码的密文解码为字节
    encrypted_data = base64.b64decode(message_base64)

    # 将密钥转换为16字节的格式（确保长度符合AES要求）
    key = key.encode('utf-8')

    # 使用AES进行解密
    cipher = AES.new(key, AES.MODE_ECB)
    decrypted_data = unpad(cipher.decrypt(encrypted_data), AES.block_size)

    # 返回解密后的字符串
    return decrypted_data.decode('utf-8')


if __name__ == '__main__':

    # 示例：生成一个16位的随机字符串
    random_number = random_string(16)
    print(f"Random Number: {random_number}")

    # 示例：AES加密
    login_form_password = "lkZxcU0KZ@"  # 模拟密码
    encrypted_password = aes_encrypt(login_form_password, random_number)
    print(f"Encrypted Password: {encrypted_password}")

    # # 示例：AES解密
    # decrypted_password = aes_decrypt(encrypted_password, random_number)
    # print(f"Decrypted Password: {decrypted_password}")

    # 输出其他生成的随机字符串
    # random_id = random_string(64)
    # print(f"Random ID: {random_id}")


